// src/stores/templateStore.ts

import { defineStore } from 'pinia'


  // in templateStore.ts
// in templateStore.ts
export interface TemplateElement {
    // ... 其他字段
    type: 'text' | 'image' | 'table';
    src?: string;
  
    // 【新增】表格相关属性
    headers?: string[];
    columnWidths?: number[];
    dataKey?: string;
  }
export const useTemplateStore = defineStore('template', {
    state: () => ({
        elements: [] as TemplateElement[],
        selectedElementId: null as string | null,
        pageSettings: { // 【新增】
          width: 595.28,
          height: 841.89,
        },
      }),

  getters: {
    selectedElement(state): TemplateElement | undefined {
      if (!state.selectedElementId) return undefined
      return state.elements.find(el => el.id === state.selectedElementId)
    },
  },

  actions: {
    addElement(type: 'text' | 'image' | 'table', payload?: { src?: string }) {
        let newElement: TemplateElement;
        
        // 【核心修正】使用 crypto.randomUUID() 生成绝对唯一的ID
        const uniqueId = crypto.randomUUID();
        if (type === 'image') {
          newElement = {
            id: uniqueId,
            type: 'image', x: 50, y: 50, width: 150, height: 100,
            src: payload?.src || 'https://placehold.co/150x100/DDDDDD/000000?text=Image',
          };
        }else if (type === 'table') { // 【新增】处理表格
            newElement = {
              id: uniqueId,
              type: 'table',
              x: 50, y: 50,
              width: 450, // 默认宽度
              height: 200, // 默认高度
              headers: ['名称', '数量', '单价'],
              columnWidths: [200, 100, 150],
              dataKey: 'items', // 默认的数据键
            };
          } else {
          newElement = {
            id: uniqueId,
            type: 'text', x: 50, y: 50, width: 150, height: 30,
            text: '双击可编辑', fontSize: 16,
          };
        }
        this.elements.push(newElement);
      },
  // 【核心修正】彻底替换 updateElement 方法
  updateElement(id: string, newProps: Partial<Omit<TemplateElement, 'id'>>) {
    const index = this.elements.findIndex(el => el.id === id);
    if (index !== -1) {
      this.elements[index] = { ...this.elements[index], ...newProps };
    }
  },
  loadTemplate(templateData: { elements: TemplateElement[], page?: any }) {
    this.elements = templateData.elements;
    // 如果加载的数据里包含页面设置，就更新它
    if (templateData.page) {
        this.pageSettings = {
            width: templateData.page.width || 595.28,
            height: templateData.page.height || 841.89,
        };
    }
    this.selectedElementId = null;
  },
    updatePageSettings(settings: { width?: number, height?: number }) {
        this.pageSettings = { ...this.pageSettings, ...settings };
      },
    selectElement(id: string | null) {
      this.selectedElementId = id;
    },
  },
})